<?php

namespace KGK\UserBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController
{
    protected function createPassword() {
        $chars = "234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $i = 0;
        $password = "";
        while ($i <= 8) {
            $password .= $chars{mt_rand(0,strlen($chars))};
            $i++;
        }
        return $password;
    }

    public function registerAction()
    {
        $form = $this->container->get('fos_user.registration.form');
        $formHandler = $this->container->get('fos_user.registration.form.handler');
        $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
        // génération aléatoire du mot de passe
        $password = $this->createPassword();

        $process = $formHandler->process($confirmationEnabled, $password);
        if ($process) {
            $user = $form->getData();

            if ($confirmationEnabled) {
                $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
                $route = 'fos_user_registration_check_email';

            } else {
                $this->authenticateUser($user);

                // envoi de la page de succès d'inscription: le mot de passe généré est affiché.
                return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:firstconfirmed.html.'.$this->getEngine(), array(
                    'user' => $user,
                    'password' => $password,
                    ));
            }

            $this->setFlash('fos_user_success', 'registration.flash.user_created');
            $url = $this->container->get('router')->generate($route);

            return new RedirectResponse($url);
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
            'form' => $form->createView(),
            'theme' => $this->container->getParameter('fos_user.template.theme'),
            ));
    }
}